package com.miyuan.net;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.miyuan.utils.ActivityUtils;
import com.miyuan.utils.SPUtils;
import com.miyuan.view.login.LoginControlActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static final int DEFAULT_TIME_OUT = 90;//超时时间
    private static final int DEFAULT_READ_TIME_OUT = 90;
    private Retrofit mRetrofit;
    private static RetrofitClient retrofitClient = null;
    private static String token;

    private RetrofitClient() {
        // 创建 OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);//连接超时时间        builder.writeTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);//写操作 超时时间
        builder.readTimeout(DEFAULT_READ_TIME_OUT, TimeUnit.SECONDS);//读操作超时时间
        // 添加公共参数拦截器
        HttpCommonInterceptor commonInterceptor = new HttpCommonInterceptor.Builder()
                .addHeaderParams("Content-type", "application/json")
                .build();

        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d("OkHttp", message);
                if (message.contains("code")) {
                    try {
                        JSONObject jsonObject = new JSONObject(message);
                        if (jsonObject.optInt("code") == 300006) {
                            SPUtils.getInstance().remove("Authorization", true);
                            ActivityUtils.finishAllActivities();
                            ActivityUtils.startActivity(LoginControlActivity.class);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        if (RetrofitClient.token != null && RetrofitClient.token.length() > 0) {
            HttpCommonInterceptor authorization = new HttpCommonInterceptor.Builder()
                    .addHeaderParams("Authorization", RetrofitClient.token)
                    .build();
            builder.addInterceptor(authorization);
        }

        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(logInterceptor);
        builder.addInterceptor(commonInterceptor);

        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(UrlPaths.BASE_URL)
                .build();
    }

//    private static class SingletonHolder {
//        private static final RetrofitClient INSTANCE = new RetrofitClient();
//    }

    /**
     * 获取RetrofitServiceManager
     *
     * @return
     */
    public static RetrofitClient getInstance() {
        //token
        String token = SPUtils.getInstance().getString("Authorization", null);
        if (!TextUtils.equals(token, RetrofitClient.token)) {
            RetrofitClient.token = token;
            return new RetrofitClient();
        } else {
            if (RetrofitClient.retrofitClient == null) {
                return new RetrofitClient();
            } else {
                return RetrofitClient.retrofitClient;
            }
        }
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>
     * @return
     */
    public <T> T create(Class<T> service) {
        return mRetrofit.create(service);
    }

}
